package com.opensource.utils;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;

import java.io.*;

/**
 * 修改已生成的sbom文件
 *
 */

public class SbomSpdxUtils {
    public static String readFile(String filePath) throws IOException {
        StringBuilder content = new StringBuilder();
        BufferedReader bufferedReader = new BufferedReader(new FileReader(filePath));
        String line;
        while ((line = bufferedReader.readLine()) != null) {
            content.append(line + "\n");
        }
        bufferedReader.close();
        return content.toString();
    }

    public static void main(String[] args) {
        try {
            String json = readFile("D:\\sbom\\json\\openEuler-20.03-LTS-SP1-update-aarch64-spdx-sbom.json");
            JSONObject sbomJsonObject = JSONObject.parseObject(json);
            sbomJsonObject.getJSONObject("creationInfo").remove("licenseListVersion");
            JSONArray jsonArray = new JSONArray(sbomJsonObject.get("packages"));
            JSONArray jsonArrayPackage = (JSONArray) jsonArray.get(0);
            for (int i = 0; i < jsonArrayPackage.size(); i++) {
                JSONObject jsonObject = jsonArrayPackage.getJSONObject(i);
                jsonObject.remove("licenseConcluded");
                jsonObject.remove("licenseDeclared");
            }
            sbomJsonObject.getJSONObject("creationInfo").put("creators","[openeuler_creator]");
            String versionFiled = sbomJsonObject.get("name").toString();
            String httpUrl = sbomJsonObject.get("documentNamespace").toString();
            int firstIndex = httpUrl.indexOf(versionFiled);
            String code = httpUrl.substring(firstIndex + versionFiled.length(), httpUrl.length() - 1);
            sbomJsonObject.put("documentNamespace","https://repo.openeuler.org/openEuler-20.03-LTS-SP1/update/aarch64/" + code);
            String content = sbomJsonObject.toString();
            writeToFile(content, "D:\\sbom\\json\\newsbom1.json");

        }catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void writeToFile(String content, String fileName) throws IOException {
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(fileName))) {
            writer.write(content);
        }
    }


}
